const express = require('express')
const Router = require('express').Router
const multer = require('multer')
const { asyncException } = require('../../util/async-execption')
const HomeManageController = require('../../controller/manage/home')
const { updateUserProfile, getAvatar, updateBranchProfile } = require('../../api/user')
const { AuthMiddleWare } = require('../../middleware/auth')
const formParser = multer({})
const router = Router()

router.get('/user/info/avatar/:username', asyncException(async (req, res) => {
    const username = req.params.username
    const stream = await getAvatar(username)
    stream.pipe(res)
}))

router.put('/user/overviews', express.json(), asyncException(async (req, res) => {
    const context = {
        user: {
            username: req.body.username,
        },
        overviews: req.body.overviews,
    }
    const homeManageController = new HomeManageController
    const succ = await homeManageController.updateOverviews(context)
    if (succ) {
        res.send({
            code: 20000,
        })
    } else {
        res.send({
            code: 20001,
        })
    }
}))

router.put('/user/profile', AuthMiddleWare(false), asyncException(async (req, res) => {
    const query = {
        username: req.__user__.username
    }
    // 单纯转发
    const response = await updateUserProfile(req, res, query)
    if (response.code === 20000) {
        res.send({
            code: 20000
        })
    }
}))

router.put('/user/repo/profile', formParser.any(), AuthMiddleWare(false), asyncException(async (req, res) => {
    const context = {
        params: {
            username: req.__user__.username,
            repo: req.body.repo,
            description: req.body.description,
            website: req.body.website,
        }
    }
    const data = await updateBranchProfile(context.params)
    if (data.code === 20000) {
        res.send({
            code: 20000,
        })
    }
}))

module.exports = router